const cloud = require("wx-server-sdk");
const excel = require('exceljs');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();
const _ = db.command;
// 获取openid
const getOpenId = async () => {
  // 获取基础信息
  const wxContext = cloud.getWXContext();
  return {
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  };
};

// 获取小程序二维码
const getMiniProgramCode = async () => {
  // 获取小程序二维码的buffer
  const resp = await cloud.openapi.wxacode.get({
    path: "pages/index/index",
  });
  const { buffer } = resp;
  // 将图片上传云存储空间
  const upload = await cloud.uploadFile({
    cloudPath: "code.png",
    fileContent: buffer,
  });
  return upload.fileID;
};

// 创建集合
const createCollection = async () => {
  try {
    // 创建集合
    await db.createCollection("peasant_data");
    await db.collection("peasant_data").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华东",
        city: "上海",
        peasant_data: 11,
      },
    });
    await db.collection("peasant_data").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华东",
        city: "南京",
        peasant_data: 11,
      },
    });
    await db.collection("peasant_data").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华南",
        city: "广州",
        peasant_data: 22,
      },
    });
    await db.collection("peasant_data").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华南",
        city: "深圳",
        peasant_data: 22,
      },
    });
    return {
      success: true,
    };
  } catch (e) {
    // 这里catch到的是该collection已经存在，从业务逻辑上来说是运行成功的，所以catch返回success给前端，避免工具在前端抛出异常
    return {
      success: true,
      data: "create collection success",
    };
  }
};

// 查询所有数据
const selectRecord = async () => {
  // 返回数据库查询结果
  return await db.collection("peasant_data").get();
};

// 根据手机号查询数据
const selectRecordByPhone = async (phone) => {
  console.log(phone,"phone");
  // 返回数据库查询结果
  return await db.collection("peasant_data").where({
    phone: _.or(_.eq(Number(phone)), _.eq(phone))
  }).get();
};

// 更新数据
const updateRecord = async (data) => {
  try {
    let id = data._id;
    let obj = JSON.parse(JSON.stringify(data));
    delete obj._id;
    await db.collection('peasant_data').doc(id).update({
      data:obj,
      success: res => {
        console.log('更新成功', res);
      },
      fail: err => {
        console.error('更新失败', err);
      }
    });
    return {
      success: true,
      data: data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 新增数据
const insertRecord = async (event) => {
  try {
    const insertRecord = event.data;
    // 插入数据
    await db.collection("peasant_data").add({
      data: {
        region: insertRecord.region,
        city: insertRecord.city,
        peasant_data: Number(insertRecord.peasant_data),
      },
    });
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 删除数据
const deleteRecord = async (event) => {
  try {
    await db
      .collection("peasant_data")
      .where({
        _id: event._id,
      })
      .remove();
    return {
      success: true,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 查询所有种植户
const queryAllUser = async ()=>{
  const res = await db.collection('peasant_data').aggregate()
  .group({
    _id: '$idNumber', // 按种植户身份证号分组
    firstRecord: { $first: '$$ROOT' } // 保留每组的第一条完整记录
  })
  .end()
  return res.list.map(item => item.firstRecord)
}

// 查询所有年份
const queryAllYear = async ()=>{
  let res =  await db.collection('peasant_data').where({
    year: _.exists(true) // 确保year字段存在
  }).field({
    year: true // 只返回year字段
  }).get({
    success: res => {
    },
    fail: err => {
      console.error('查询失败:', err)
    }
  })
  return [...new Set(res.data.map(item => item.year))]
}
// 根据种植户身份证号查询订单数据
const queryOrderById = async (idNumber)=>{
  return await db.collection('peasant_data').where({
    idNumber: _.eq(idNumber) 
  }).get();
}
// 根据订单id查询订单数据
const queryOrderByOrderId = async (orderId)=>{
  return await db.collection('peasant_data').where({
    _id: _.eq(orderId) 
  }).get();
}
// 根据订单id查询订单数据
const queryPeasant = async (event)=>{
  const { year, peasantName, idNumber } = event;
  try {
    // 基础条件：year必须存在
    const condition = { year: year };
    // 动态添加模糊查询条件
    if (peasantName && idNumber) {
      condition.peasantName = db.RegExp({ regexp: peasantName, options: 'i' });
      condition.idNumber = db.RegExp({ regexp: idNumber, options: 'i' });
    } else if (peasantName) {
      condition.peasantName = db.RegExp({ regexp: peasantName, options: 'i' });
    } else if (idNumber) {
      condition.idNumber = db.RegExp({ regexp: idNumber, options: 'i' });
    }
    const result = await db.collection('peasant_data')
      .where(condition)
      .get();
    return { code: 0, data: result.data };
  } catch (err) {
    console.error(err);
    return { code: -1, message: '查询失败，请检查参数或权限' };
  }
}
const exportXlsxFile = async (event)=>{
   // 创建一个表格
   const workbook = new excel.Workbook();
   // 创建一个sheet
   const worksheet = workbook.addWorksheet(event.year+'年收购数据');
   // 假设data是一个二维数组是我们要导出去的数据，代表表格数据  row 是每一行数据
   // 这里我们伪造假数据 你们到时候可以从前端传进来
   var data = event.tableData;
   data.forEach((row, rowIndex) => {
     row.forEach((value, colIndex) => {
       // 设置单元格的值  
       worksheet.getCell(rowIndex + 1, colIndex + 1).value = value;
       // 假设你想让所有内容都居中，并且设置自动列宽（这可能需要一些自定义逻辑）  
       worksheet.getColumn(colIndex + 1).alignment = {
         horizontal: 'center',
         vertical: 'middle'
       };
       // 注意：exceljs没有直接的“自动列宽”功能，但你可以根据内容长度来动态设置列宽 如果没有达到你们的效果，可以尝试调一下5这个数值
       worksheet.getColumn(colIndex + 1).width = Math.max(20, value.toString().length * 2);
     });
   });
 
   // 将工作簿写入文件 返回buffer流
   const buffer = await workbook.xlsx.writeBuffer();
   // 把excel文件保存到云存储里 并将下载链接返回到前端
   var fileName = `export_${Date.now()}.xlsx`;
   let res = await cloud.uploadFile({
     cloudPath: 'exportExcel/' + fileName,
     fileContent: buffer, //excel二进制文件
   })
   if (!res.fileID) {
     return '上传失败'
   } else {
     // 获取临时链接路径
     let res2 = await cloud.getTempFileURL({
       fileList: [res.fileID],
     })
     if (!res2.fileList.length) {
       return '获取下载地址失败'
     } else {
       let fileUrl = res2.fileList[0].tempFileURL
       console.log('文件下载链接' + fileUrl);
       return {
         url1:fileUrl,
         url2:fileName,
         fileId:res.fileID
       }  
     }
   }
}
// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.type) {
    case "getOpenId":
      return await getOpenId();
    case "getMiniProgramCode":
      return await getMiniProgramCode();
    case "createCollection":
      return await createCollection();
    case "selectRecord":
      return await selectRecord();
    case "selectRecordByPhone":
      return await selectRecordByPhone(event.phone);
    case "updateRecord":
      return await updateRecord(event.data);
    case "insertRecord":
      return await insertRecord(event);
    case "deleteRecord":
      return await deleteRecord(event);
    case "queryAllUser":
      return await queryAllUser();
    case "queryOrderById":
      return await queryOrderById(event.idNumber);
    case "queryOrderByOrderId":
      return await queryOrderByOrderId(event.orderId);
    case "queryAllYear":
      return await queryAllYear();
    case "queryPeasant":
      return await queryPeasant(event);
    case "exportXlsxFile":
      return await exportXlsxFile(event);
  }
};
